package com.example.teamtribe.common.model;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import com.example.teamtribe.Application;
import com.example.teamtribe.common.Back;
import com.example.teamtribe.utils.HttpUtil;
import com.example.teamtribe.utils.URLStore;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class FileModel {

    private static volatile FileModel instance;
    private FileModel() {}
    public static FileModel getInstance() {
        if (instance == null) {
            synchronized (FileModel.class) {
                if (instance == null) {
                    instance = new FileModel();
                }
            }
        }
        return instance;
    }

    /***
     *
     * @param moduleId 0头像，1帖子附加的图片，2社团相册的图片
     */
    public void upload(String token, File file, int moduleId, final Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("TeamTribeToken", token);
        params.put("moduleId", moduleId + "");
        Map<String, File> files = new HashMap<>();
        files.put("file", file);
        HttpUtil.post(URLStore.FILE_UPLOAD, params, files, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                back.failure(HttpUtil.getFailureMeg());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject object = new JSONObject(response.body().string());
                    Log.d("上传文件", object.toString());
                    final int status = object.getInt("code");
                    if (status != 0) {
                        back.failure(HttpUtil.getCodeMeg(status));
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString("fileName", object.getString("fileName"));
                        back.success(bundle);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void download(final String fileName, int moduleId, final FileBack fileBack) {
        if (fileName.equals("00000000000000000000000000000000")) {
            fileBack.loadSuccess(fileName);
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("fileName", fileName);
        params.put("moduleId", moduleId + "");
        HttpUtil.post(URLStore.FILE_DOWNLOAD, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                fileBack.failure(HttpUtil.getFailureMeg());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream inputStream = response.body().byteStream();
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();

                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                inputStream.close();
                byte[] image = outStream.toByteArray();
                outStream.close();
                response.close();

                FileOutputStream fos = Application.getContext().openFileOutput(fileName, Context.MODE_PRIVATE);
                fos.write(image);
                fos.flush();
                fos.close();

                fileBack.loadSuccess(fileName);
            }
        });
    }

    public interface FileBack extends Back {
        void loadSuccess(String fileName);
    }

    public interface UploadComplete {
        void complete(List<String> fileNames);
    }
}
